package indi.wshape1.takeawaydeliveryinfo.servlet;

import indi.wshape1.takeawaydeliveryinfo.domain.Admin;
import indi.wshape1.takeawaydeliveryinfo.domain.Block;
import indi.wshape1.takeawaydeliveryinfo.domain.Group;
import indi.wshape1.takeawaydeliveryinfo.domain.Sender;
import indi.wshape1.takeawaydeliveryinfo.service.AdminService;
import indi.wshape1.takeawaydeliveryinfo.service.RootService;
import indi.wshape1.takeawaydeliveryinfo.service.SenderService;
import indi.wshape1.takeawaydeliveryinfo.service.UtilService;
import indi.wshape1.takeawaydeliveryinfo.service.impl.AdminServiceImpl;
import indi.wshape1.takeawaydeliveryinfo.service.impl.SenderServiceImpl;
import indi.wshape1.takeawaydeliveryinfo.util.StringUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author Wshape1
 * @create 2022-11-19 15:03
 */

@WebServlet(name = "ChangeServlet", value = {"/change"})
public class ChangeServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //  接收 change.js 的changeInfo() changePassword() 的POST请求

        resp.setContentType("text/html; charset=UTF-8");
        String func = req.getParameter("func");
        PrintWriter writer = resp.getWriter();
        try {
            //      0 - 未知错误  1 - 成功  2 - 密码错误
            int state = 0;
            String user = (String) req.getSession().getAttribute("user");
            String type = (String) req.getServletContext().getAttribute(user);

            if ("changeInfo".equals(func)) {
                String name = req.getParameter("name");

                if ("sender".equals(type)) {
                    SenderService senderService = new SenderServiceImpl();
                    Sender sender = senderService.getByPhone(user);
                    sender.setName(name);
                    senderService.update(sender, sender.getPhone());
                } else if ("admin".equals(type)) {
                    AdminService adminService = new AdminServiceImpl();
                    Admin admin = adminService.getByPhone(user);
                    admin.setName(name);
                    adminService.update(admin, admin.getPhone());
                }

                state = 1;
            } else if ("changePassword".equals(func)) {
                String oldPwd = req.getParameter("oldPwd");
                String newPwd = req.getParameter("newPwd");

                if ("sender".equals(type)) {
                    SenderService senderService = new SenderServiceImpl();
                    Sender sender = senderService.getByPhone(user);

                    if (oldPwd.equals(sender.getPassword())) {
                        sender.setPassword(newPwd);
                        senderService.update(sender, sender.getPhone());
                        state = 1;
                    } else {
                        state = 2;
                    }
                } else if ("admin".equals(type)) {
                    AdminService adminService = new AdminServiceImpl();
                    Admin admin = adminService.getByPhone(user);

                    if (oldPwd.equals(admin.getPassword())) {
                        admin.setPassword(newPwd);
                        adminService.update(admin, admin.getPhone());
                        state = 1;
                    } else {
                        state = 2;
                    }
                } else if ("root".equals(type)) {
                    RootService rootService = new RootService();
                    if (oldPwd.equals(rootService.getRootPassword())) {
                        rootService.updateRootPassword(newPwd);
                        state = 1;
                    } else {
                        state = 2;
                    }
                }
            }
            writer.print(state);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();

        req.getSession().setAttribute("page", 1);   //初始化 page.js 查询数据的页数

        //  page.html 下拉选择 组别 选项获取  page.js changeGroupSelect 发送的请求
        String selectedBlock = req.getParameter("selectedBlock");
        if (!StringUtil.isEmpty(selectedBlock)) {

            StringBuilder stringBuilder = new StringBuilder("[");

            List<Group> list = UtilService.groupService.getListByBlock(selectedBlock);

            for (Group group : list) {
                stringBuilder.append("\"").append(group.getName()).append("\",");
            }
            if (list.size() > 0)
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);

            stringBuilder.append("]");
            writer.print(stringBuilder);
            return;
        }
        //

        String user = (String) req.getSession().getAttribute("user");
        String type = (String) req.getServletContext().getAttribute(user);
        String name = UtilService.getPersonName(user, type);

        StringBuilder stringBuilder = new StringBuilder("[{\"name\": \"" + name + "\", \"type\": \"" + type + "\", \"user\": \"" + user + "\"}, {");


        // 判断是否是 change.js setPreName() 发送的请求， 是则不需要执行以下操作
        if (!(!StringUtil.isEmpty(req.getParameter("onlyGetName")) && "true".equals(req.getParameter("onlyGetName"))))
            if ("sender".equals(type)) {
                Sender sender = UtilService.senderService.getByPhone(user);
                stringBuilder.append("\"block\": \"").append(sender.getBlock()).append("\", \"group\": \"").append(sender.getGroup()).append("\"");
            } else if ("admin".equals(type)) {
                Admin admin = UtilService.adminService.getByPhone(user);
                stringBuilder.append("\"block\": \"").append(admin.getBlock()).append("\", \"groups\": [");

                List<Group> groups = UtilService.groupService.getListByBlock(admin.getBlock());

                for (Group group : groups) {
                    stringBuilder.append("\"").append(group.getName()).append("\",");
                }
                if (groups.size() > 0)
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                stringBuilder.append("]");
            } else if ("root".equals(type)) {

                stringBuilder.append("\"blocks\": [");

                List<Block> blocks = UtilService.blockService.getList();

                for (Block block : blocks) {
                    stringBuilder.append("\"").append(block.getName()).append("\",");
                }
                if (blocks.size() > 0)
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                stringBuilder.append("]");

            }
        //

        stringBuilder.append("}]");
        writer.print(stringBuilder);
    }
}
